<?php
namespace app\crm\model;

use think\facade\Db;
use app\admin\model\Common;

use app\mini\controller\GetAccessToken;
use app\mini\model\SendUrlModel;

class SendMsgModel extends Common
{


    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer_transfer_shop';

    /////////////////////////////////////////////////////////////短信发送/////////////////////////////////////////////////
    /**
     * 短信发送
     * 满意度调查
     *
     */
    public function shortMessage($type,$tel,$sendData)
    {
        echo "短信分类：".$type;
        echo "<br/>";

        echo "手机号码：".$tel;
        echo "<br/>";

    }

    /**
     * 短信发送
     * serviceLog
     *
     */
    public function shortMessageServiceLog($tel,$sendData)
    {
        $params = [
            'apikey' => '9616eb7d8bd7ff79ca24af3fad8f192b',
            'mobile' => $tel,
            'tpl_id' => '5650336',
            'tpl_value' =>('#time#').'='.$sendData['time'].'&'.('#groupId#').'='.$sendData['group'].'&'.('#content#').'='.$sendData['content'],
        ];

        $param = '';

        foreach($params as $key => $val){

            $param .= urlencode($key).'='.urlencode($val).'&';

        }

        $param = substr($param,0,strlen($param)-1);

        $url = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";

        $model = new SendUrlModel();

        $res = $model->send_url($url, $param);

        return $res;

    }

    /**
     * 模板短信无变量群发
     * serviceLog
     *
     */
    public function shortMessageMassHair($tel,$sendData)
    {
        $params = [
            'apikey' => '9616eb7d8bd7ff79ca24af3fad8f192b',
            'mobile' => $tel,
            'tpl_id' => $sendData['tpl_id'],
            'tpl_value' =>""
        ];

        $url = "https://sms.yunpian.com/v2/sms/tpl_batch_send.json";

        $model = new SendUrlModel();

        $res = $model->send_mass_url($url, $params);

        return $res;

    }



    //////////////////////////////////////////////////////////////公众号推送/////////////////////////////////////////////////////////
    /**
     * 发送请求
     */
    public function http_curl($url,$type,$res,$arr)
    {
        /**
         * $url 请求的url
         * $type 请求类型
         * $res 返回数据类型
         * $arr post请求参数
         */
        $ch=curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        $output = curl_exec($ch);
        curl_close($ch);
        if($res=='json'){
            return json_decode($output,true);
        }

    }


    public function wx_send($openid,$status)
    {
        // echo "模板消息";
        // exit;

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        // 公众号
        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

        ];

        $data = $model->send_url($url,$jsonData);

        $res = json_decode($data,true);

        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;

        $token = $res['access_token'];

        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;

        $dt = array(
            "touser" => $openid,
            'template_id'  => 'xl3Z_wkofGfGtgad2UkIKLktqyh8jYqNjToHvNTYetM',
            'url'   => "",
            'miniprogram' => array(
                'appid' => 'wxfee2f64c9d301f2f',
                'pagepath' => 'pages/questionPaper/questionPaper?status='.$status,
            ),
			'data' => array(
                'first' => array('value' => '欣奕'),
                'keyword1' =>array('value' => '欣奕用户'),
                'keyword2' =>array('value' => date('Y-m-d H:i:s')),
                'remark' =>array('value' => '点击此处评价此次客服质量。'),
            ),
        );


		$postjson = json_encode($dt);

        // echo $postjson;

        // exit;
		$resder = $this->http_curl($posturl,'post','json',$postjson);

        // var_dump($resder);

    }
    //发送微信消息模板
    public function wx_send_msgtemplate($sendData){

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        // 公众号
        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',
        ];

        $data = $model->send_url($url,$jsonData);

        $res = json_decode($data,true);

        $token = $res['access_token'];
        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
        $dt = array(
            "touser" => $sendData['open_id'],
            'template_id'  => $sendData['template_id'],
            'url'   => $sendData['url'],
            'miniprogram' =>$sendData['miniprogram'],
			'data' =>$sendData['data']
        );
		$postjson = json_encode($dt);
		$resder = $this->http_curl($posturl,'post','json',$postjson);
    }





    public function wx_send_service_log(){



        $fomateToken = file_get_contents('./token_file/accessTokenWX.json');

        $token_info = json_decode($fomateToken,true);

        $nowTime = time();

        if($nowTime < $token_info['expireTime']){

            $ACCESS_TOKEN = $token_info['access_token'];

        }else{

            // $getAccessTokenModel = new GetAccessToken();

            // $ACCESS_TOKEN = $getAccessTokenModel->get_access_token_wx();

            $model = new SendUrlModel();

            $url = "https://api.weixin.qq.com/cgi-bin/token";

            $jsonData = [

                'grant_type' => 'client_credential',

                'appid'      => 'wx7cde54d2bb9607e6',

                'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

            ];

            $data = $model->send_url($url,$jsonData);

            $fomateToken = json_decode($data,true);

            $fomateToken['expireTime'] = time() + $fomateToken['expires_in'] - 10;

            // echo "<pre>";
            // print_r($fomateToken);
            // echo "</pre>";

            $newData = json_encode($fomateToken);

            file_put_contents('./token_file/accessTokenWX.json', $newData);

            $ACCESS_TOKEN = $fomateToken['access_token'];

        }

        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$ACCESS_TOKEN;

        $dt = array(
            "touser" => 'orXbIs9RDp16tEveSqcWIYB82R6c',
            'template_id'  => 'TxPFSBEQ2y7868ZmaL7T8GAv12I5QKh4lvhctMgW0gc',
            'url'   => "",
			'data' => array(
                'thing5'       => array('value' => '大学路店'),
                'thing3'       => array('value' => '无针水光:本次消耗1次,剩余6次;疤痕多疗程:本次消耗1次,剩余1次;'),
                'short_thing4' => array('value' => '1'),
                'number9'      => array('value' => '3'),
                'time11'       => array('value' => date('Y-m-d H:i:s')),
            ),
        );


		$postjson = json_encode($dt);

        // echo $postjson;

        // exit;
		$resder = $this->http_curl($posturl,'post','json',$postjson);

        var_dump($resder);

    }

    public function everydaytask()
    {
        $cj_days = [1,3,5,10];

        $addData = [];

        $send_date = date('Y-m-d').' 11:30:00';

        $send_time = strtotime($send_date);

        foreach ($cj_days as $key => $value) {

            $days = $value*30;

            $time_t = strtotime('-'.$days.' days');

            $date = date('Y-m-d',$time_t);

            $start_t = strtotime($date);

            $end_t = strtotime($date.' 23:59:59');

            $where = [];

            array_push($where,['cj_time','between',"$start_t,$end_t"]);

            array_push($where,['cj_money',">=",'500']);

            array_push($where,['cj_order_id',">",'0']);

            $customerList = Db::name('customer')->where($where)->column('id');

            // if($value == '1'){

            //     $customerList = [360027,403409];

            // }


            $where = [];

            array_push($where,['customerId','in',$customerList]);

            $unionids = Db::name('mini_program_fans')->where($where)->column('unionId','customerId');



            foreach ($customerList as $k => $v) {

                $unionid = $unionids[$v] ?? '';

                if($unionid){

                    $where = [];

                    array_push($where,['unionid','=',$unionid]);

                    $wx_openid = Db::name('wx_gzh_fans')->where($where)->value('openid');

                    if($wx_openid){

                        $today = date("Y-m-d");

                        $today_s = strtotime($today);

                        $today_e = strtotime($today.' 23:59:59');

                        $res = Db::name('a_send_jl')->where([['openid','=',$wx_openid],['send_time','between',"$today_s,$today_e"]])->select()->toArray();

                        if(empty($res)){

                            $one = [];

                            $one['customer_id'] = $v;

                            $one['openid'] = $wx_openid;

                            $one['send_time'] = $send_time;

                            $one['send_status'] = $value;

                            array_push($addData,$one);

                        }


                    }

                }

            }

        }

        $res = Db::name("a_send_jl")->insertAll($addData);

        // exit;

    }

    public function send_tuisong()
    {


        $nowTime = date('H:i:s');
        // $nowTime = "17:32:00";

        if($nowTime>'10:00:00' && $nowTime<'18:00:00'){

            $nowDate = date('Y-m-d');

            $nowDate_s = strtotime($nowDate);

            $nowDate_e = strtotime($nowDate.' 23:59:59');

            $sendList = Db::name('a_send_jl')->where('send_time','between',"$nowDate_s,$nowDate_e")->select()->toArray();

            // echo "<pre>";
            // print_r($sendList);
            // echo "</pre>";
            // exit;

            foreach ($sendList as $key => $value) {

                if($value['send_num'] == '0'){

                    $this->wx_send($value['openid'],$value['send_status']);

                    $save = [];

                    $save['send_num'] = '1';

                    $save['send_time'] = bcadd($value['send_time'],86400*5,0);

                    $res = Db::name('a_send_jl')->where('id','=',$value['id'])->update($save);

                }else{

                    $where = [];

                    array_push($where,['customer_id','=',$value['customer_id']]);

                    array_push($where,['questionnaire_id','=',$value['send_status']]);

                    $isSubmit = Db::name('question_customer')->where($where)->find();

                    if(empty($isSubmit)){

                        $this->wx_send($value['openid'],$value['send_status']);

                    }

                    Db::name('a_send_jl')->where('id','=',$value['id'])->delete();

                }

            }

        }

    }


    public function service_log_send(){

    }

    public function wx_send_cs($openid,$status)
    {
        // echo "模板消息20231219";
        // exit;

        $model = new SendUrlModel();

        $url = "https://api.weixin.qq.com/cgi-bin/token";

        // 公众号
        $jsonData = [

            'grant_type' => 'client_credential',

            'appid'      => 'wx7cde54d2bb9607e6',

            'secret'     => '1aa86183eca8d6ebf854cbc0349543df',

        ];

        $data = $model->send_url($url,$jsonData);

        $res = json_decode($data,true);

        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;

        $token = $res['access_token'];

        $posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;

        $dt = array(
            "touser" => $openid,
            'template_id'  => 'xl3Z_wkofGfGtgad2UkIKLktqyh8jYqNjToHvNTYetM',
            'url'   => "",
            'miniprogram' => array(
                'appid' => 'wxfee2f64c9d301f2f',
                'pagepath' => 'pages/activity20231212/activity20231212?status='.$status,
            ),
			'data' => array(
                'first' => array('value' => '欣奕'),
                'keyword1' =>array('value' => '欣奕用户'),
                'keyword2' =>array('value' => date('Y-m-d H:i:s')),
                'remark' =>array('value' => '点击此处评价此次客服质量。'),
            ),
        );


		$postjson = json_encode($dt);

		$resder = $this->http_curl($posturl,'post','json',$postjson);

        // var_dump($resder);

    }


}

?>
